import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, register, logout } from '@/api/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)

  const doLogin = async (loginForm) => {
    try {
      const { data } = await login(loginForm)

      // 设置3分钟后过期
      const expireTime = new Date().getTime() + 50 * 60 * 1000
      localStorage.setItem('expireTime', expireTime)

      localStorage.setItem('user_token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
      userInfo.value = data.userInfo

      ElMessage.success('登录成功')
      return data
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  const doLogout = () => {
    userInfo.value = null
    localStorage.removeItem('user_token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('expireTime')
    router.push('/login')
    ElMessage.success('已退出登录')
  }

  return {
    userInfo,
    login: doLogin,
    logout: doLogout,
    register
  }
})
